package com.javasm.finance.controller;

import com.javasm.finance.entity.CodeAndMsg;
import com.javasm.finance.entity.Menu;
import com.javasm.finance.entity.ReturnEntity;
import com.javasm.finance.entity.User;
import com.javasm.finance.service.MenuService;
import com.javasm.finance.service.UserService;
import com.javasm.finance.service.impl.MenuServiceImpl;
import com.javasm.finance.service.impl.UserServiceImpl;
import com.javasm.finance.util.RespUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/login")
public class LoginController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("userName");
        String userPwd = req.getParameter("userPwd");
        UserService userService=new UserServiceImpl();
        User loginUser = userService.findLoginUser(userName, userPwd);
        ReturnEntity re=new ReturnEntity();
        if (loginUser!=null){
            //登录成功
            //设置最后登录时间
            userService.editLoginTime(loginUser.getUserId());
            HttpSession session = req.getSession();
            User user = new User(userName, userPwd);
            session.setAttribute("user",user);
            List<String> loginUserMenuUrl = userService.findLoginUserMenuUrl(loginUser.getUserId());
            session.setAttribute("loginUserMenuUrl",loginUserMenuUrl);
            MenuService menuService=new MenuServiceImpl();
            List<Menu> menuList = menuService.findMenu(loginUser.getUserId());
            session.setAttribute("menuList",menuList);
            re.setReturnCode(CodeAndMsg.LOGIN_SUCCESS.getReturnCode());
            re.setReturnMsg(CodeAndMsg.LOGIN_SUCCESS.getReturnMsg());
        }else {
            re.setReturnCode(CodeAndMsg.LOGIN_FAILED.getReturnCode());
            re.setReturnMsg(CodeAndMsg.LOGIN_FAILED.getReturnMsg());
        }
        RespUtils.handleResp(resp, re);
    }
}
